#!/bin/bash

###############################################################################################
# Because the resource `docker-depend.tar.gz` is not full enough to build the docker image,   #
# we need to make a patch for it.                                                             #
#                                                                                             #
# The reason of `not-enough` is that, when installing `libssl-dev`, it depends on `libssl1.1` #
# and `libssl5`.                                                                              #
#                                                                                             #
# However, the last one is missed in the given resource, and solution of this                 #
# is to add something in Dockerfile.                                                          #
# As for the first one, its version need to be `1.1.1-1ubuntu2.1~18.04.23`, but the given     #
# version in `docker-depend.tar.gz` is `1.1.1-1ubuntu2.1~18.04.21`, so we need to use `04.23` #
# instead of `04.21`.                                                                         #
#                                                                                             #
# And this script will make the patch to change the version of `libssl1.1` from `04.21` to    #
# `04.23`.                                                                                    #
###############################################################################################

SCRIPT_DIR=$(pwd)
WORK_DIR="$SCRIPT_DIR/temp-for-docker-depend"
RESOURCES_DIR="$SCRIPT_DIR/build/resources"
LOG_FILE="$WORK_DIR/patch.log"

mkdir -p "$WORK_DIR"
pushd "$WORK_DIR" > /dev/null

mv "$RESOURCES_DIR/docker-depend.tar.gz" "$WORK_DIR"
tar -zxf "docker-depend.tar.gz"
mv "docker-depend.tar.gz" "docker-depend-backup.tar.gz"
cd "docker-depend/"

# Correct the file name in the rm command
rm "libssl-dev_1.1.1-1ubuntu2.1~18.04.21_arm64.deb" 2>> "$LOG_FILE"

if [ $? -ne 0 ]; then
    echo "Can't find libssl-dev_1.1.1-1ubuntu2.1~18.04.21_arm64.deb" | tee -a "$LOG_FILE"
    exit 1
fi

# correct source
wget -c "https://launchpad.net/~ubuntu-security/+archive/ubuntu/ppa/+build/26217236/+files/libssl-dev_1.1.1-1ubuntu2.1~18.04.23_arm64.deb" 2>> "$LOG_FILE"

cd ..
tar -czvf "docker-depend.tar.gz" "docker-depend" 2>> "$LOG_FILE"
mv "docker-depend.tar.gz" "$RESOURCES_DIR"

popd > /dev/null
echo "Patch for docker-depend finished."
